package com.sport.booking.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author zecheng
 */
@Service
public class WxService {

        private static final String WX_API_URL = "https://api.weixin.qq.com/sns/jscode2session";
        private static final String APPID = "wx2ffc265202f470cd";
        private static final String SECRET = "5ff4041f558e97d5719c47a8259b7e97";

        public String getOpenId(String code) {
            String url = WX_API_URL + "?appid=" + APPID + "&secret=" + SECRET + "&js_code=" + code + "&grant_type=authorization_code";

            // 发起HTTP请求
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {

                JSONObject json = new JSONObject(Boolean.parseBoolean(response.getBody()));
                return json.getString("openid");
            }

            throw new RuntimeException("获取openid失败");
        }

}
